package com.cy.web;


import com.alibaba.fastjson.JSONArray;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.cy.Redis.CacheRedisService;
import com.cy.Service.CheckPointService;
import com.cy.Service.FronthostService;
import com.cy.Service.Question1Service;
import com.cy.bean.*;


import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.xml.transform.Result;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FonthostController {
    @Value("${server.port}")
    private String port;
    @Autowired
    private FronthostService fronthostService;
    @Autowired
    private CacheRedisService cacheRedisService;
    @Autowired
    private CheckPointService checkPointService;


    @RequestMapping("/getfonthost/{openid}")
    public @ResponseBody
    Map<String,Object> getAllQuestion(@PathVariable String openid){
        //注释到这里结束

        //根据openid获取用户信息
        Fronthost user = cacheRedisService.getObject(openid,Fronthost.class);
        Map<String,Object> map = new HashMap<>();
        map.put("port",port);
        map.put("user",user);
        System.out.println("已完成");
        return map;
    }

    @RequestMapping("/getUserOpenId")
    @ResponseBody
    public String getUserOpenId( String encryptedData, String iv, String code) throws JSONException {

        System.out.println(encryptedData);
        System.out.println(iv);
        System.out.println(code);

        // 小程序唯一标识 (在微信小程序管理后台获取)
        String wxspAppid = "wx877c0c3167f08dcc";
        // 小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "63739ed6518756e0e297c6b746574b69";
        // 授权（必填）
        String grant_type = "authorization_code";

        // 请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析相应内容（转换成json对象）
        //获取注册时间
        Date current = new Date();//实例化Date对象
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String regtime = formatter.format(current);
        System.out.println(regtime);
        // 解析相应内容（转换成json对象）
        String openid = null;
        org.codehaus.jettison.json.JSONObject json = null;
        try {
            json = new org.codehaus.jettison.json.JSONObject(sr);
            // 用户的唯一标识（openid）
            openid = json.get("openid").toString();
        } catch (org.codehaus.jettison.json.JSONException e) {
            e.printStackTrace();
        }
        //通过openid查到用户实体 是否有此用户
        Fronthost fronthost = fronthostService.selectUserOne(openid);
        if(fronthost==null){
            // 没有此用户的话进行添加 1、基础信息 2、详细信息
            int a = fronthostService.insrtUser(openid,regtime);
            Fronthost fronthost2 = fronthostService.selectUserOne(openid);
            int b = fronthostService.insrtFrontslave(String.valueOf(fronthost2.getUid()));
        }
        Fronthost fronthost3 = fronthostService.selectUserAll(openid);
        String str = JSONArray.toJSONString(fronthost3);
        //存进redis
        cacheRedisService.add(openid,fronthost3);
        System.out.println("唯一表示"+openid);
        return str;

    }
    @RequestMapping("/fare")
    @ResponseBody
    public String uselist(Frontreport frontreport) {
        System.out.println("发热上报");
        //存进redis
        cacheRedisService.add("examine",1);

        CodeTool codeTool = new CodeTool();
        int a = fronthostService.insertFrontReport(frontreport);
        if(a==1){
            codeTool.refreshCode("17750639356");
            codeTool.setToken("17750639356");
        Map<String,CodeTool>codeMap= CodeTool.getCodeToolMap();
        String code = codeTool.getCode();
            codeMap.put("17750639356",codeTool);
            String content="已有用户进行发热上报，请及时进行处理！";
            String success = SMSTool.sendVerificationCode(content,"17750639356");
            System.out.println(success);
            return "suscess";
        }else{
            return "fail";
        }
    }

    @RequestMapping("/getcode")
    @ResponseBody
    public String getcode(Fronthost fronthost) {
        System.out.println("获取验证码");
        String rmCode = getCode();
//        com.aliyun.dysmsapi20170525.Client client = null;
//        try {
//            client = this.createClient("ACCESS_KEY_ID", "ACCESS_KEY_SECRET");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        SendSmsRequest sendSmsRequest = new SendSmsRequest()
//                .setSignName("阿里云短信测试")
//                .setTemplateCode("SMS_154950909")
//                .setPhoneNumbers(fronthost.getPhone())
//                .setTemplateParam("{\"code\":\""+rmCode+"\"}");
//        RuntimeOptions runtime = new RuntimeOptions();
//        SendSmsResponse resp = null;
//        try {
//            resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        try {
//            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        CodeTool codeTool = new CodeTool();
            codeTool.refreshCode(fronthost.getPhone());
            codeTool.setToken(fronthost.getPhone());
            Map<String,CodeTool>codeMap= CodeTool.getCodeToolMap();
            codeMap.put(fronthost.getPhone(),codeTool);
            String content="[疫防控]提醒您，行程卡登陆验证码为:---"+rmCode+"---！";
            SMSTool.sendVerificationCode(content,fronthost.getPhone());
        return rmCode;
    }
    //返回随机验证码
    public static String getCode(){
        String str="0123456789";
        String code="";
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            code+=ch;
        }
        return code;
    }
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId("LTAI5tGbjDeWJi82NtVsoyiq")
                // 您的 AccessKey Secret
                .setAccessKeySecret("LqBStpVSU35ofijXEkcOACPZcNm2FS");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    @RequestMapping("/getHeSuan")
    @ResponseBody
    public String getHeSuan(String uid) {
        System.out.println("获取核酸报告");
        //通过uid获取核酸id
        List<Report> reports = fronthostService.selseReportList(uid);
        String a = JSONArray.toJSONString(reports);
        return a;
    }


    @RequestMapping("/getfamliy")
    @ResponseBody
    public String getfamliy(String uid) {
        System.out.println("获取亲友对象集合");
        //通过uid获取亲友对象
        List<Fronthost> familys = fronthostService.selectFamily(uid);
        String a = JSONArray.toJSONString(familys);
        return a;
    }

    @RequestMapping("/getfamliyone")
    @ResponseBody
    public String getfamliyone(String uid) {
        System.out.println("获取亲友对象单独的所有信息");
        //通过uid获取亲友对象
        Fronthost familys = fronthostService.selectFamilyone(uid);
        String a = JSONArray.toJSONString(familys);
        return a;
    }

    @RequestMapping("/addfamliyy")
    @ResponseBody
    public String addfamliyy(String fname,String fnum,String uid) {
        System.out.println("添加亲友");
        //通过名字和身份证号码获取亲友对象
        Fronthost fronthost = fronthostService.Familyone(fname,fnum);
        //判断是不是自己
        if(Integer.valueOf(uid)==(int)fronthost.getUid()){
            return "chongfu";
        }
        //判断是否已添加过此亲友
        Family family = fronthostService.selechongfu(Integer.parseInt(uid), (int)fronthost.getUid());

        if(family==null){
            //根据自己id和亲友id添加亲友
            int b = fronthostService.insertfamily(Integer.valueOf(uid), (int) fronthost.getUid());
            if(b==1){
                String a= "sucess";
                return a;
            }else{
                String a= "fail";
                return a;
            }
        }else{
            return "fail";
        }

    }

    @RequestMapping("/deletfamliy")
    @ResponseBody
    public void deletfamliy(String uid,String fuid) {
        System.out.println("删除亲友");
        //删除亲友
        fronthostService.deleFamily(uid,fuid);

    }

    @RequestMapping("/getitinerary")
    @ResponseBody
    public String getitinerary(String uphone,String nowday,String sevenday) {
        System.out.println("通过电话拿到用户的行程记录");
        //通过电话拿到用户的行程记录
        List<Frontnote>frontnotes = fronthostService.selectFrontnote(uphone,nowday,sevenday);
        String a = JSONArray.toJSONString(frontnotes);
        return a;
    }

    @RequestMapping("/getcheckpoint")
    @ResponseBody
    public List<CheckPoint> getCheckPointList(){
        List<CheckPoint> list=checkPointService.getcheckpointlist();
        return list;
    }

    @RequestMapping("/getcheckpointdetail")
    @ResponseBody
    public List<CheckPoint> getCheckPointDetail(@RequestParam("data")String data){
        List<CheckPoint> list=checkPointService.getcheckpointdetail(data);
        return list;
    }
    @RequestMapping("/realname")
    @ResponseBody
    public String getRealname(String uname, String phone, String idnumber, String uid ){
        System.out.println("实名认证");
        //修改名字、电话、身份证号码  赋予健康码颜色 默认绿色
        int a = fronthostService.updateRealName(uname,phone,idnumber,uid);
        Fronthost f = fronthostService.selectFamilyone(uid);
        if(f.getStatus()==0){//未修改
            return "fail";
        }else{//修改成功返回实体类
            String b = JSONArray.toJSONString(f);
            return b;
        }
    }

    @RequestMapping("/mydata")
    @ResponseBody
    public String getMydata(String uname, String phone, String idnumber, String nativeplace, String nowprovince, String nowcity, String nowarea, String nowaddress, String uid){
        System.out.println("个人信息");
        Fronthost a = fronthostService.updateMydata(uname,phone,idnumber,nativeplace,nowprovince,nowcity,nowarea,nowaddress,uid);
        Fronthost fronthost = fronthostService.selectUserAddress(uid);
        String str = JSONArray.toJSONString(fronthost);
        cacheRedisService.add(uid,fronthost);
        System.out.println(str);
        return str;
    }
    @RequestMapping("/getorder")
    @ResponseBody
    public String getorder(String uid){
        System.out.println("核酸预约列表");
        List<Orderrecord> orderrecordList = fronthostService.ordlist(uid);
        String a = JSONArray.toJSONString(orderrecordList);
        return a;
    }


    SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");

    @PostMapping("/uploadImg")
    public String uploadImg(MultipartFile uploadFile, HttpServletRequest req){
        //获取文件名
        String fileName = uploadFile.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        //添加日期
        String format = sd.format(new Date());
        //指定本地文件夹存储图片
        String filePath = "E:/Data/uploadFile/"+format+"/";
        File file = new File(filePath,fileName);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            file.createNewFile();
            uploadFile.transferTo(new File(filePath+fileName));
            return  "http://"+req.getRemoteHost()+":"+req.getServerPort()+"/"+format+"/"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }




}
